﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.MenuRole;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.MenuRole
{
    public class MeunRoleCommandHandle:IRequestHandler<MeunRoleCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<MenuRoleModel> MenuRoleDal;

        public MeunRoleCommandHandle(IBaseRepository<MenuRoleModel> menuRoleDal)
        {
            MenuRoleDal = menuRoleDal;
        }

        public async Task<ApiResult<int>> Handle(MeunRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                //查询并删除该角色已分配的所有菜单
                var res = MenuRoleDal.GetAll().Where(x=>x.RoleId == request.RoleId).ToList();
                await MenuRoleDal.Del(res);
                List<MenuRoleModel> models = new List<MenuRoleModel>();

                // 通过foreach构建新的菜单角色关联列表
                foreach (var model in request.MenuId)
                {
                    models.Add(new MenuRoleModel()
                    {
                        MenuId = model,
                        RoleId = request.RoleId,
                    });
                }
                //批量插入新的菜单角色关联
                int count = await MenuRoleDal.AddAll(models);
                if (count > 0)
                {
                    result.Code = ApiEnum.Success;
                    result.Message = "分配成功";
                }
                else
                {
                    result.Code = ApiEnum.Error;
                    result.Message = "分配失败";
                }
                tran.Complete();
                return await Task.FromResult(result);
            }
        }




    }
}
